<template>
  <GapedColumn>
    <AddButton buttonText="新增规则" @click="handleAdd" />
    <el-table key="id" :data="computedConditions" style="width: 100%">
      <el-table-column prop="name" label="条件名称" width="180" />
      <el-table-column prop="field" label="字段" width="120" />
      <el-table-column prop="parseJson" label="解析JSON" width="100">
        <template #default="scope">
          {{ scope.row.parseJson ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="computedConditions.some(c => c.parseJson)"
        prop="keyPath"
        label="Key路径"
        width="180"
      />
      <el-table-column
        v-if="computedConditions.some(c => c.parseJson)"
        prop="jsonValueOperator"
        label="运算符"
        width="100"
      />
      <el-table-column
        v-if="computedConditions.some(c => c.parseJson)"
        prop="jsonValue"
        label="值"
        width="120"
      />
      <el-table-column
        v-if="computedConditions.some(c => c.parseJson)"
        prop="jsonValueType"
        label="值类型"
        width="100"
      />
      <el-table-column
        v-if="computedConditions.some(c => !c.parseJson)"
        prop="keyExp"
        label="Key表达式"
        width="180"
      />
      <el-table-column
        v-if="computedConditions.some(c => !c.parseJson)"
        prop="seperator"
        label="分隔符"
        width="100"
      />
      <el-table-column
        v-if="computedConditions.some(c => !c.parseJson)"
        prop="valueExp"
        label="值表达式"
        width="180"
      />
      <el-table-column
        v-if="computedConditions.some(c => !c.parseJson)"
        prop="value"
        label="匹配值"
        width="120"
      />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <EditButton @click="handleEdit(scope.row)" />
          <DeleteButton @click="handleDelete(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
  </GapedColumn>

  <AddConditionDialog
    ref="addConditionDialog"
    :updateCallback="handleCondtionChanged"
  />
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import AddConditionDialog from './AddConditionDialog.vue'
import { chain } from 'lodash'
import useApi from '@/core/apiStore'
import ConditionModel from '@/models/ConditionModel'
import AddButton from '@/components/AddButton.vue'
import { GapedColumn } from '@/core/components'
import {
  showSuccessSaveMessage,
  checkDuplicateCondition,
  showAlert,
  showSuccessDeleteMessage,
  showConfirm,
} from '@/utils'

const apiStore = useApi()

const conditions = ref([])

const computedConditions = computed(() => {
  return conditions.value.map((item, index) => ({
    ...item,
    id: index, // 添加id属性，使用数组索引作为唯一标识
  }))
})

const addConditionDialog = ref()

onMounted(async () => {
  const result = await apiStore.getCondtions({})

  conditions.value = Object.keys(result).map(key => ({
    ...result[key],
  }))
})

const handleConfirm = async () => {
  const result = chain(conditions.value)
    .map(item => [item.name, item])
    .fromPairs()
    .value()
  await apiStore.setConditions(result)
}

const handleAdd = () => {
  addConditionDialog.value.show()
}

const handleEdit = (row: ConditionModel) => {
  const condition = computedConditions.value.find(item => item.id === row.id)
  if (condition) {
    addConditionDialog.value.show(condition)
  }
}

const handleCondtionChanged = async (newCondition: any) => {
  const isDuplicate = checkDuplicateCondition(
    computedConditions.value,
    newCondition
  )

  if (isDuplicate) {
    showAlert('条件名称已存在，请使用其他名称')
    return false
  }

  // 如果是编辑操作，更新现有条件
  if (newCondition.id !== undefined) {
    const index = computedConditions.value.findIndex(
      c => c.id === newCondition.id
    )
    if (index !== -1) {
      conditions.value[index] = { ...newCondition }
    }
  } else {
    // 新增条件
    conditions.value.push({
      ...newCondition,
    })
  }
  await saveCondtions()
  showSuccessSaveMessage()
  return true
}

const saveCondtions = async () => {
  await apiStore.setConditions(
    chain(conditions.value)
      .map(item => [item.name, item])
      .fromPairs()
      .value()
  )
}
const handleDelete = (row: any) => {
  const index = conditions.value.findIndex(item => item.name === row.name)
  if (index !== -1) {
    showConfirm(`确认删除"${row.name}"吗`, async () => {
      conditions.value.splice(index, 1)
      await saveCondtions()
      showSuccessDeleteMessage()
    })
  }
}
</script>
